var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('./libs/log').logger;
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session         = require('express-session');
var commService = require('./services/commService');
var async = require('async');
var config = require('./conf/config.js');
var wxConfig = config['wechat'];


var index = require('./routes/index');
// var users = require('./routes/users');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
// app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));



//session中间件
// var sessionMiddleware = session({
//   store: new RedisStore({
//     host: "115.238.54.182",
//     port: 6380,
//     db: 10,
//     pass:'d0SK8CJr6Fg0UeZnOs50Dd8QWmyHj5A'
//   }),
//   resave:true,
//   saveUninitialized:true,
//   secret: 'appins(24n@__ ',
//   key: 'fn',
//   cookie:{
//     //     天* 小时*分钟*秒*毫秒
//     maxAge: 1* 1  *60  *60*1000}
// });

app.use(cookieParser(''));
app.use(session({
  secret: '12345',
  cookie: {maxAge: 1*24*3600*1000 },  //设置maxAge是80000ms，即80s后session和相应的cookie失效过期
  resave: true,
  saveUninitialized: true,
}));

app.use(function(req,res,next){
  logger.debug('openId:'+req.session.openid);
  logger.debug('openId:'+req.path);
  if(req.session.openid == undefined && req.path != '/rest/wx/wxauth'){
    async.waterfall([
        function(callbk){
          commService.sessionGet(req,callbk);
        },
        function(data,callbk){
          logger.debug(JSON.stringify(data));
          if(!data){
            var wxurl = wxConfig.auth_url.replace('(appid)',wxConfig.appid)
                .replace('(redirect_uri)',config['murl']+'/rest/wx/wxauth')
                .replace('(scope)', 'snsapi_userinfo')
                .replace('(state)','login');
            logger.debug(wxurl);
            callbk({code:0,url:wxurl},null);
          }else{
            req.session.acc_name=data.name;
            req.session.channel_name=data.channel_name;
            req.session.org_id=data.org_id;
            req.session.channel_id=data.channel_id;
            req.session.emp_id = data.emp_id;
            req.session.realname = data.realname;
            req.session.acctype = data.pay_method;
            req.session.openid = data.openid;
            req.session.wxnickname = data.wxnickname;
            req.session.avatar = data.avatar;
            callbk(null,{code:0,msg:'OK'});
          }
        }
      ],function(err,result){
        if(err){
          logger.debug(err.url);
          return res.redirect(err.url);
        }else {
          next();
        }
      });
  }else{
    next();
  }
})

app.use('/', index);
// app.use('/users', users);


// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
